<?php

namespace App\Http\Controllers;

use App\Models\Roles;
use App\Models\Users;
use Illuminate\Http\Request;

class UserController extends Controller{

    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        try {
            $params = [
                'nickname'   => (string)$request->get('nickname',''),
            ];
            $lists = Users::select('id','username','avatar','nickname','role_id','status','login_at')
                ->where(function ($query) use ($params) {
                    if($params['nickname']) {
                        $query ->where('nickname','like','%' . $params['nickname'] . '%');
                    }
                })
                ->orderBy('id', 'desc')
                ->paginate(10);
            $roles = Roles::getRoles();
            $this->stateToText($lists,[
                'status' => Users::STATUS_TEXT,
                'role_id'=> $roles
            ]);
            return $this->returnJson(0,'',$lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }

    }

    /**
     * 更新/新增数据
     * @param $data 表单数据
     * @return bool
     */
    public function update(Request $request){
        try {
            $data = $request->all();
            //先查后更
            $info = Users::find($data['id']);
            $data['password'] = bcrypt($info['openid']);
            if(empty($info)){
                return $this->returnJson(1,'抱歉，数据不存在');
            }
            $info->update($data);
            return $this->returnJson(0, '更新用户成功，页面即将跳转...');
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }
    }


    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destory(Request $request){
        try {
            $id = $request->get('id');
            Users::destroy($id);
            return $this->returnJson(0);
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }
    }

    /**
     * 登陆用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(){
        $user = auth()->guard('api')->user();
        $role = $user->role()->get();
        return $this->returnJson(0,'',['user'=>$user,'role'=>$role]);
    }






}